include(['com.unknown.Constants', 'com.unknown.Config'], 
function(){
	
	declare('com.unknown.Console');
com.unknown.Console = function(url){
	this.client = null;
	this.url = url;
	this.subscriptionId = null;
	this.connected = false;
	this.onError = function(error){
		console.log('Failed to connect: ' + error);
	};
	this.connect = function(){
		var scope = this;
		$(function(){
			scope.client = Stomp.client(url);
			scope.client.onerror = function(frame){
				console.error( frame.toString() )
				console.log( frame );
			}
			scope.client.connect(username, sessionId, function(){
				scope.onConnect();
			});	
		})
		
	};

    /**
     *
     * @param player
     */
	this.inputChanged = function(update){
		if(!this.connected || !update) return;
		
		var cmd = {
			name : update.id,
			vector : update.vector,
			x : update.roomX,
			y : update.roomY,
			roomid : update.roomId
		};
		this.client.send('/topic/chat', {}, JSON.stringify(cmd));		
	};
	this.onConnect = function(){
		this.connected = true;
		var scope = this;
		console.log('Connected');
		this.subscriptionId = this.client.subscribe('/topic/chat', function(msg){
			scope.onUpdate(msg);
		}, this.onError);
		
		this.inputChanged();
	};
	this.onUpdate = function(msg){		
		var data = eval('(' + msg.body + ')');
		
		if( data.name == player.name ) return;

        var notOnScreen = true;
        var cell = eGrid.findCellByRoomId( data.roomid );
        if( cell ){
            var position = cell.grid.node.toWorldCoordinate({x:data.x, y:data.y});
            if( gamewindow.containsPoint(position) ){
                if( !gamewindow.entities[data.name] ){
                    var e = new world.Entity();
                    e.name = data.name;
                    e.images = ['../images/characters/male_Walk.png'];
                    gamewindow.addEntity(e);
                }
                gamewindow.entities[data.name]._input.reset(data.vector.x, data.vector.y);
                gamewindow.entities[data.name].x = position.x;
                gamewindow.entities[data.name].y = position.y;
                notOnScreen = false;
            }
        }
        if(notOnScreen){
            var entity = gamewindow.entities[data.name];
            if( entity ){
                gamewindow.entities[data.name] = null;
            }
        }
	};
};
});